import { Injectable } from '@nestjs/common';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Book } from './entities/book.entity';
import { Repository } from 'typeorm';
import { ResultData } from '../../utils/result';

@Injectable()
export class BooksService {
    constructor(
        @InjectRepository(Book) private readonly user: Repository<Book>,
    ) {}
    async create(createBookDto: CreateBookDto) {
        const res = await this.user.findOne({
            where: { name: createBookDto.name },
        });
        if (!res) {
            const res = await this.user.insert(createBookDto);
            if (res) {
                return new ResultData(200, '添加成功');
            }
        }
        return new ResultData(500, '添加失败');
    }

    async statisticsTotal() {
        const query = await this.user
            .createQueryBuilder('')
            .select('type') // 选择 type 字段
            .addSelect('COUNT(type)', 'count') // 统计相同 type 的数量
            .groupBy('type') // 按 type 分组
            .getRawMany();
        const res = query.map((it) => ({ ...it, count: Number(it.count) }));
        return new ResultData(200, '', res);
    }

    async findBook(id: number) {
        const res = await this.user.findOne({ where: { id } });
        return res;
    }

    update(id: number, updateBookDto: UpdateBookDto) {
        return `This action updates a #${id} book`;
    }

    remove(id: number) {
        return `This action removes a #${id} book`;
    }
}
